package com.scy.controller2;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;

@Controller
@RequestMapping("/path")
public class DownloadController {

    @RequestMapping(value = "/download1")
    public ResponseEntity<byte[]> downloadFile(HttpSession session) throws IOException {
        // 获取文件路径（示例：项目内文件）
        String fileName="WEB-INF/classes/萌宝宝.jpg";

        String realPath = session.getServletContext().getRealPath(fileName);
        System.out.println("realPath = " + realPath);
        File file = new File(realPath);

        // 读取文件字节
        byte[] bytes = Files.readAllBytes(file.toPath());

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        String fileName1 = file.getName();
        System.out.println("真实的文件名是:" + fileName1);
        String fileName1UrlEncode = URLEncoder.encode(fileName1, "UTF-8");
        System.out.println("fileName1UrlEncode = " + fileName1UrlEncode);

        headers.add("Content-Disposition",
                "attachment;filename=" + fileName1UrlEncode );

        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }
}
